package com.zll.dms.aop;

import com.zll.dms.exception.MyBaseException;
import com.zll.dms.pojo.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.session.UnknownSessionException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    /**
     * @valid参数校验异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultData validationException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            List<String> messages = new ArrayList<>();
            allErrors.forEach(p->{
                FieldError fieldError = (FieldError) p;
                log.error("参数格式错误：参数对象：{}；字段：{}；错误原因:{}", fieldError.getObjectName(), fieldError.getField(), fieldError.getDefaultMessage());
                messages.add(fieldError.getDefaultMessage());
            });
            return ResultData.error(StringUtils.join(messages,","));
        }
        return ResultData.error("参数格式错误");
    }

    /**
     * 全局异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResultData globalExceptionHandler(Exception e) {
        //未登录
        if (e instanceof UnauthenticatedException || e instanceof AuthenticationException || e instanceof UnknownSessionException) {
            return ResultData.createNoLogin();
        }else if (e instanceof UnauthorizedException || e instanceof AuthorizationException) {
            //无权限
            return ResultData.createNoRight();
        } else if (e instanceof MyBaseException) {
            //自定义异常
            log.warn("自定义异常",e);
            return ResultData.error(e.getMessage());
        } else {
            //其他异常
            log.error("未知异常", e);
            return ResultData.error("系统开小差了");
        }
    }
}
